<template>
  <div class="homework-container">
    <h1>我的作业</h1>

    <div class="user-info">
      <p>欢迎，{{ userProfile.fullName }}同学</p>
      <router-link to="/student/dashboard">返回Dashboard</router-link>
    </div>

    <!-- 状态筛选条件区域（值为字符串1/2/3/4，对应未提交/已提交/已批改/已退回） -->
    <div class="status-filter">
      <label class="filter-label">作业状态：</label>
      <div class="status-buttons">
        <button
            class="status-btn"
            :class="{ active: currentStatus === '' }"
            @click="changeStatus('')"
        >
          全部
        </button>
        <button
            class="status-btn"
            :class="{ active: currentStatus === '1' }"
            @click="changeStatus('1')"
        >
          未提交
        </button>
        <button
            class="status-btn"
            :class="{ active: currentStatus === '2' }"
            @click="changeStatus('2')"
        >
          已提交
        </button>
        <button
            class="status-btn"
            :class="{ active: currentStatus === '3' }"
            @click="changeStatus('3')"
        >
          已批改
        </button>
        <button
            class="status-btn"
            :class="{ active: currentStatus === '4' }"
            @click="changeStatus('4')"
        >
          已退回
        </button>
      </div>
    </div>

    <!-- 作业列表 -->
    <div class="homework-list">
      <div class="list-header">
        <h2>作业列表</h2>
        <button @click="loadHomeworkList" class="refresh-btn">刷新</button>
      </div>

      <div v-if="loading" class="loading">加载中...</div>

      <div v-else-if="homeworkList.length > 0" class="homework-items">
        <div
            v-for="homework in homeworkList"
            :key="homework.id"
            class="homework-item"
            :class="{
            'submitted': getSubmissionStatus(homework) === 2 || getSubmissionStatus(homework) === 3,
            'expired': isExpired(homework.dueDate)
          }"
        >
          <!-- 作业标题与截止时间 -->
          <div class="homework-header">
            <h3>{{ homework.title }}</h3>
            <span class="due-date" :class="{ 'expired': isExpired(homework.dueDate) }">
              截止时间: {{ formatDateTime(homework.dueDate) }}
              <span v-if="isExpired(homework.dueDate)" class="expired-tag">已截止</span>
            </span>
          </div>

          <!-- 作业内容 -->
          <div class="homework-content">
            <p>{{ homework.content }}</p>
          </div>

          <!-- 作业元信息 -->
          <div class="homework-meta">
            <span>学科: {{ homework.subjectName }}</span>
            <span>发布时间: {{ formatDateTime(homework.createdAt) }}</span>
          </div>

          <!-- 作业状态 + 退回原因提示 -->
          <div class="homework-status">
            <span :class="getStatusClass(homework)">{{ getStatusText(homework) }}</span>

            <!-- 退回状态时提示：教师评语含退回原因 -->
            <span
                v-if="getSubmissionStatus(homework) === 4"
                class="rejection-hint"
            >
              教师评语中包含退回原因，点击查看
            </span>
          </div>

          <!-- 作业操作按钮 -->
          <div class="homework-actions">
            <!-- 未提交 + 未截止：提交作业 -->
            <button
                v-if="getSubmissionStatus(homework) === 1 && !isExpired(homework.dueDate)"
                @click="showSubmitModal(homework)"
                class="submit-btn"
            >
              提交作业
            </button>

            <!-- 未提交 + 已截止：已截止（置灰） -->
            <button
                v-if="getSubmissionStatus(homework) === 1 && isExpired(homework.dueDate)"
                class="disabled-btn"
                disabled
            >
              已截止
            </button>

            <!-- 已提交/已批改/已退回：查看提交（含教师评语） -->
            <button
                v-if="getSubmissionStatus(homework) >= 2"
                @click="showSubmissionDetail(homework)"
                class="view-btn"
            >
              查看提交
            </button>

            <!-- 已退回 + 未截止：重新提交 -->
            <button
                v-if="getSubmissionStatus(homework) === 4 && !isExpired(homework.dueDate)"
                @click="showSubmitModal(homework, true)"
                class="resubmit-btn"
            >
              重新提交
            </button>

            <!-- 已退回 + 已截止：已截止（置灰） -->
            <button
                v-if="getSubmissionStatus(homework) === 4 && isExpired(homework.dueDate)"
                class="disabled-btn"
                disabled
            >
              已截止，无法重新提交
            </button>
          </div>
        </div>
      </div>

      <div v-else class="no-homework">
        <p>暂无符合条件的作业</p>
      </div>
    </div>

    <!-- 1. 提交作业模态框（含重新提交） -->
    <div v-if="showSubmitModalFlag" class="modal" @click="closeSubmitModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>{{ isResubmit ? '重新提交作业' : '提交作业' }} - {{ selectedHomework.title }}</h2>
          <span class="close" @click="closeSubmitModal">&times;</span>
        </div>
        <div class="modal-body">
          <!-- 重新提交时：显示教师评语（含退回原因） -->
          <div v-if="isResubmit && currentSubmission?.feedback" class="teacher-feedback">
            <strong>📝 教师评语（含退回原因）：</strong>
            <p>{{ currentSubmission.feedback }}</p>
          </div>

          <form @submit.prevent="submitHomework">
            <div class="form-group">
              <label for="content">作业内容:</label>
              <textarea
                  id="content"
                  v-model="submissionForm.content"
                  required
                  placeholder="请输入作业内容"
                  rows="8"
              ></textarea>
            </div>
            <div class="form-group">
              <label for="attachmentUrl">附件链接 (可选):</label>
              <input
                  type="text"
                  id="attachmentUrl"
                  v-model="submissionForm.attachmentUrl"
                  placeholder="请输入附件链接"
              />
            </div>
            <div class="form-actions">
              <button
                  type="submit"
                  class="submit-btn"
                  :disabled="isExpired(selectedHomework.dueDate)"
              >
                {{ isResubmit ? '重新提交' : '提交' }}
              </button>
              <button type="button" class="cancel-btn" @click="closeSubmitModal">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 2. 查看提交详情模态框 -->
    <div v-if="showDetailModalFlag" class="modal" @click="closeDetailModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>作业提交详情</h2>
          <span class="close" @click="closeDetailModal">&times;</span>
        </div>
        <div class="modal-body">
          <div v-if="currentSubmission">
            <div class="detail-item">
              <label>提交内容:</label>
              <div class="submission-content">{{ currentSubmission.content }}</div>
            </div>
            <div v-if="currentSubmission.attachmentUrl" class="detail-item">
              <label>附件:</label>
              <a :href="currentSubmission.attachmentUrl" target="_blank" class="attachment-link">查看附件</a>
            </div>
            <div class="detail-item">
              <label>提交时间:</label>
              <span>{{ formatDateTime(currentSubmission.submittedAt) }}</span>
            </div>
            <div v-if="currentSubmission.grade" class="detail-item">
              <label>成绩:</label>
              <span>{{ currentSubmission.grade }}</span>
            </div>
            <!-- 教师评语（合并退回原因） -->
            <div v-if="currentSubmission.feedback" class="detail-item teacher-feedback">
              <label>教师评语:</label>
              <div class="feedback-content">
                {{ currentSubmission.feedback }}
                <!-- 退回状态时添加明确标识 -->
                <span v-if="getSubmissionStatus(selectedHomework) === 4" class="rejection-tag">
                  （包含退回原因）
                </span>
              </div>
            </div>
          </div>
          <div v-else>暂无提交信息</div>
        </div>
      </div>
    </div>

    <!-- 提示信息 -->
    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
    <div v-if="successMessage" class="success-message">{{ successMessage }}</div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  name: 'StudentHomework',
  setup() {
    // 基础数据
    const userProfile = ref({});
    const homeworkList = ref([]);
    const loading = ref(false);
    const errorMessage = ref('');
    const successMessage = ref('');

    // 状态筛选相关：参数名=submissionStatus，值=字符串1/2/3/4，空字符串表示全部
    const currentStatus = ref('');

    // 提交作业相关
    const showSubmitModalFlag = ref(false);
    const selectedHomework = ref(null);
    const isResubmit = ref(false);
    const submissionForm = ref({ assignmentId: null, content: '', attachmentUrl: '' });

    // 查看详情相关
    const showDetailModalFlag = ref(false);
    const currentSubmission = ref(null);

    // 1. 加载用户信息
    const loadUserProfile = async () => {
      try {
        const res = await fetch('/user/profile', {
          method: 'GET',
          credentials: 'include',
          headers: { 'Content-Type': 'application/json' }
        });
        const result = await res.json();
        if (result.code === 1) userProfile.value = result.data;
        else errorMessage.value = result.msg || '获取用户信息失败';
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      }
    };

    // 2. 加载作业列表（核心：传递submissionStatus参数，值为字符串1/2/3/4）
    const loadHomeworkList = async () => {
      try {
        loading.value = true;
        errorMessage.value = '';

        // 构建URL：参数名=submissionStatus，参数值=currentStatus（字符串1/2/3/4/空）
        const url = new URL('/student/homework/list', window.location.origin);
        url.searchParams.append('submissionStatus', currentStatus.value);

        const res = await fetch(url.toString(), {
          method: 'GET',
          credentials: 'include',
          headers: { 'Content-Type': 'application/json' }
        });

        const result = await res.json();
        if (result.code === 1) {
          homeworkList.value = result.data || [];
        } else {
          errorMessage.value = result.msg || '获取作业列表失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      } finally {
        loading.value = false;
      }
    };

    // 3. 切换状态筛选（值为字符串1/2/3/4）
    const changeStatus = (status) => {
      if (currentStatus.value !== status) {
        currentStatus.value = status; // status为''/'1'/'2'/'3'/'4'（均为字符串）
        loadHomeworkList();
      }
    };

    // 4. 显示提交弹窗（含重新提交）
    const showSubmitModal = async (homework, resubmit = false) => {
      selectedHomework.value = homework;
      isResubmit.value = resubmit;
      submissionForm.value = {
        assignmentId: homework.id,
        content: '',
        attachmentUrl: ''
      };

      // 重新提交时加载当前提交信息（含教师评语）
      if (resubmit) {
        try {
          const res = await fetch(`/student/homework/submission/${homework.id}`, {
            method: 'GET',
            credentials: 'include'
          });
          const result = await res.json();
          if (result.code === 1 && result.data) {
            currentSubmission.value = result.data;
            submissionForm.value.content = result.data.content || '';
            submissionForm.value.attachmentUrl = result.data.attachmentUrl || '';
          }
        } catch (err) {
          console.error('加载提交历史失败', err);
        }
      }

      showSubmitModalFlag.value = true;
    };

    // 5. 提交作业
    const submitHomework = async () => {
      if (isExpired(selectedHomework.value.dueDate)) {
        errorMessage.value = '作业已截止，无法提交';
        return;
      }
      try {
        const res = await fetch(isResubmit.value ? '/student/homework/resubmit' : '/student/homework/submit', {
          method: 'POST',
          credentials: 'include',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(submissionForm.value)
        });
        const result = await res.json();
        if (result.code === 1) {
          successMessage.value = isResubmit.value ? '重新提交成功' : '提交成功';
          closeSubmitModal();
          await loadHomeworkList();
        } else {
          errorMessage.value = result.msg || (isResubmit.value ? '重新提交失败' : '提交失败');
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      }
    };

    // 6. 查看提交详情（含教师评语）
    const showSubmissionDetail = async (homework) => {
      try {
        selectedHomework.value = homework;
        const res = await fetch(`/student/homework/submission/${homework.id}`, {
          method: 'GET',
          credentials: 'include'
        });
        const result = await res.json();
        if (result.code === 1) {
          currentSubmission.value = result.data;
          showDetailModalFlag.value = true;
        } else {
          errorMessage.value = result.msg || '获取详情失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，获取详情失败';
      }
    };

    // 工具方法：状态映射（1-未提交，2-已提交，3-已批改，4-已退回）
    const getSubmissionStatus = (homework) => homework.submissionStatus ? parseInt(homework.submissionStatus) : 1;
    const getStatusText = (homework) => {
      const status = getSubmissionStatus(homework);
      switch(status) {
        case 1: return isExpired(homework.dueDate) ? '未完成(已截止)' : '未完成';
        case 2: return '已提交';
        case 3: return '已批改';
        case 4: return '已退回';
        default: return '未知状态';
      }
    };
    const getStatusClass = (homework) => {
      const status = getSubmissionStatus(homework);
      return status === 1
          ? (isExpired(homework.dueDate) ? 'status-expired' : 'status-pending')
          : status === 2 ? 'status-submitted' : status === 3 ? 'status-graded' : 'status-rejected';
    };
    const formatDateTime = (dateString) => {
      if (!dateString) return '无';
      return new Date(dateString).toLocaleString('zh-CN', {
        year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit', minute: '2-digit', second: '2-digit'
      });
    };
    const isExpired = (dateString) => dateString && new Date(dateString) < new Date();

    // 关闭弹窗方法
    const closeSubmitModal = () => {
      showSubmitModalFlag.value = false;
      selectedHomework.value = null;
      isResubmit.value = false;
    };
    const closeDetailModal = () => {
      showDetailModalFlag.value = false;
      currentSubmission.value = null;
      selectedHomework.value = null;
    };

    // 生命周期
    onMounted(() => {
      loadUserProfile();
      loadHomeworkList(); // 初始加载全部作业（submissionStatus为空字符串）
    });

    return {
      userProfile, homeworkList, loading, errorMessage, successMessage,
      currentStatus,
      showSubmitModalFlag, selectedHomework, isResubmit, submissionForm, currentSubmission,
      showDetailModalFlag,
      loadHomeworkList, changeStatus,
      showSubmitModal, closeSubmitModal,
      submitHomework, showSubmissionDetail, closeDetailModal,
      getSubmissionStatus, getStatusText, getStatusClass, formatDateTime, isExpired
    };
  }
};
</script>

<style scoped>
/* 状态筛选样式 */
.status-filter {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.filter-label {
  font-weight: bold;
  color: #555;
  white-space: nowrap;
}

.status-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.status-btn {
  padding: 6px 15px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s ease;
}

.status-btn:hover {
  border-color: #409EFF;
  color: #409EFF;
}

.status-btn.active {
  background-color: #409EFF;
  color: white;
  border-color: #409EFF;
}

/* 原有样式保持不变 */
.homework-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.homework-container h1 {
  text-align: center;
  color: #333;
}

.user-info {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info a {
  color: #409EFF;
  text-decoration: none;
}

.user-info a:hover {
  text-decoration: underline;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.list-header h2 {
  margin: 0;
  color: #333;
}

.refresh-btn {
  padding: 8px 15px;
  background-color: #9E9E9E;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.refresh-btn:hover {
  background-color: #757575;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #666;
}

.homework-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.homework-item {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  transition: all 0.3s ease;
}

.homework-item.submitted {
  border-color: #67C23A;
}

.homework-item.expired {
  background-color: #fdf7f7;
}

.homework-item:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.homework-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

.homework-header h3 {
  margin: 0;
  color: #333;
  flex: 1;
}

.due-date {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  margin-left: 10px;
}

.due-date.expired {
  color: #f56c6c;
  font-weight: bold;
}

.expired-tag {
  display: inline-block;
  background-color: #f56c6c;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 3px;
  margin-left: 5px;
}

.homework-content p {
  margin: 0 0 15px 0;
  color: #555;
  line-height: 1.5;
}

.homework-meta {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #999;
  border-top: 1px solid #eee;
  padding-top: 10px;
  margin-bottom: 10px;
  flex-wrap: wrap;
  gap: 10px;
}

.homework-status {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.homework-status span {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: bold;
}

.rejection-hint {
  color: #e6a23c;
  font-size: 13px;
  padding: 4px 8px;
  background-color: #fff8e1;
  border-radius: 4px;
  margin-left: 5px;
}

.status-pending {
  background-color: #f5f5f5;
  color: #999;
}

.status-expired {
  background-color: #fff3cd;
  color: #e6a23c;
}

.status-submitted {
  background-color: #e8f4fd;
  color: #409EFF;
}

.status-graded {
  background-color: #d4edda;
  color: #67C23A;
}

.status-rejected {
  background-color: #f8d7da;
  color: #f56c6c;
}

.status-unknown {
  background-color: #f5f5f5;
  color: #999;
}

.homework-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.submit-btn, .view-btn, .cancel-btn, .resubmit-btn, .disabled-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.submit-btn {
  background-color: #67C23A;
  color: white;
}

.submit-btn:hover:enabled {
  background-color: #55a52a;
}

.submit-btn:disabled {
  background-color: #b3e19d;
  cursor: not-allowed;
}

.resubmit-btn {
  background-color: #e6a23c;
  color: white;
}

.resubmit-btn:hover {
  background-color: #d48806;
}

.view-btn {
  background-color: #409EFF;
  color: white;
}

.view-btn:hover {
  background-color: #337ecc;
}

.cancel-btn {
  background-color: #9E9E9E;
  color: white;
}

.cancel-btn:hover {
  background-color: #757575;
}

.disabled-btn {
  background-color: #ccc;
  color: #666;
  cursor: not-allowed;
}

.no-homework {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

/* 模态框样式 */
.modal {
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  border-radius: 5px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  color: #333;
}

.close {
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
  color: #999;
}

.close:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group textarea:focus {
  border-color: #409EFF;
  outline: none;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.3);
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-item label {
  display: block;
  font-weight: bold;
  margin-bottom: 5px;
  color: #555;
}

.submission-content, .feedback-content {
  background-color: #f9f9f9;
  padding: 10px;
  border-radius: 4px;
  white-space: pre-wrap;
  line-height: 1.5;
}

.attachment-link {
  color: #409EFF;
  text-decoration: none;
}

.attachment-link:hover {
  text-decoration: underline;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 15px;
  border-radius: 5px;
  margin-top: 20px;
}

.success-message {
  background-color: #d4edda;
  color: #155724;
  padding: 15px;
  border-radius: 5px;
  margin-top: 20px;
}

/* 教师评语样式（包含退回原因） */
.teacher-feedback {
  margin-bottom: 20px;
}
.teacher-feedback .feedback-content {
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  line-height: 1.6;
  border-left: 3px solid #409EFF;
}
.rejection-tag {
  display: inline-block;
  margin-left: 8px;
  color: #e6a23c;
  font-size: 12px;
  background-color: #fff3cd;
  padding: 2px 6px;
  border-radius: 3px;
}

/* 重新提交时的教师评语区域 */
.modal-body .teacher-feedback {
  background-color: #fff8e1;
  padding: 12px 15px;
  border-radius: 4px;
  color: #856404;
}
.modal-body .teacher-feedback p {
  margin: 5px 0 0 0;
  line-height: 1.6;
}

@media (max-width: 600px) {
  .homework-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .due-date {
    margin-left: 0;
  }

  .homework-meta {
    flex-direction: column;
    gap: 5px;
  }

  .homework-actions {
    flex-direction: column;
  }

  .form-actions {
    flex-direction: column;
  }

  .modal-content {
    width: 95%;
  }

  .status-filter {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>